﻿using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.UI;

namespace Solution2
{
    public class ColorTLBehaviour : PlayableBehaviour
    {
        public ColorTLTrack Owner;
        public Text Target;

        public override void OnGraphStart(Playable playable)
        {
            Target = (playable.GetGraph().GetResolver() as PlayableDirector).GetGenericBinding(Owner) as Text;
        }

        /// <summary>
        /// TrackBehaviour的OnPlay是Track的启动时
        /// </summary>
        /// <param name="playable"></param>
        /// <param name="info"></param>
        public override void OnBehaviourPlay(Playable playable, FrameData info)
        {
            if (Target != null)
            {
                Target.color = Color.white;
            }
        }

        public override void OnBehaviourDelay(Playable playable, FrameData info)
        {
        }

        public override void OnBehaviourPause(Playable playable, FrameData info)
        {
            if (Target != null)
            {
                Target.color = Color.white;
            }
        }

        public override void PrepareFrame(Playable playable, FrameData info)
        {
            base.PrepareFrame(playable, info);
        }

        public override void ProcessFrame(Playable playable, FrameData info, object playerData)
        {
            int clipCount = playable.GetInputCount();

            int index = 0;
            for (int i = 0; i < clipCount; i++)
            {
                float weight = playable.GetInputWeight(i);
                if (weight > 0f)
                {
                    index = i;
                    break;
                }
            }

            ColorTLAsset curAsset = null;
            foreach (var itr in Owner.GetClips())
            {
                if (index == 0)
                {
                    curAsset = itr.asset as ColorTLAsset;
                }
                index--;
            }

            if (Target != null)
            {
                Target.color = curAsset.Param;
            }
        }
    }
}